package com.file.parser;

import com.file.bo.ResponseData;
import com.file.bo.mail.BCM2;
import com.file.bo.mail.BCMTran2;
import com.file.constant.ErrorCode;
import com.file.parser.traprange.PDFTableExtractor;
import com.file.util.JsonUtils;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.*;
import technology.tabula.detectors.SpreadsheetDetectionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 交通银行pdf(无交易对手版)流水解析
 * @author anyspa
 */

@Slf4j
public class BCMPdfParser2 extends BasePdfParser {

    public ResponseData<String> parseBCMPdfToJson(String daId, String filePath) {
        log.info("parseBCMPdfToJson2 started, daId:{}", daId);
        String json;

        try {
            BCM2 bcm = parseBCMPdf(filePath);
            json = JsonUtils.convertObjectToJson(bcm);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseBCMPdfToJson2 failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseBCMPdfToJson2 completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private BCM2 parseBCMPdf(String filePath) {
        BCM2 bcm = parseBCMHeader(filePath);

        List<BCMTran2> bcmTrans = parseBCMTrans(filePath);

        bcm.setBcmTrans(bcmTrans);

        log.info("BCM2 = {}", bcm);
        return bcm;
    }

    private BCM2 parseBCMHeader(String filePath) {
        BCM2 bcm = new BCM2();

        // 1. 读取文件
        File pdf = new File(filePath);

        // 2. pdfbox读取PDDocument
        try (PDDocument pdfDocument = PDDocument.load(pdf)) {
            // 3. tabula新建ObjectExtractor和NurminenDetectionAlgorithm，同时准备接收表格Rectangle的结构
            ObjectExtractor objectExtractor = new ObjectExtractor(pdfDocument);
            SpreadsheetDetectionAlgorithm detectionAlgorithm = new SpreadsheetDetectionAlgorithm();

            // 4. 获取每页的PageIterator
            PageIterator pages = objectExtractor.extract();
            // 获取第一页
            Page page = pages.next();
            List<Rectangle> tablesOnPage = detectionAlgorithm.detect(page);
            Rectangle rectangle = tablesOnPage.get(0);
            Page area = page.getArea(rectangle);

            // 6.通过table位置获取表格具体内容
            SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm();
            List<Table> table = sea.extract(area);
            // 默认每页只有一个表格，因此获取第0个table
            Table t = table.get(0);

            getHeaderByTable(t, bcm);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return bcm;
    }

    private void getHeaderByTable(Table t, BCM2 bcm) {
        for (int i = 0; i < t.getRowCount(); i++) {
            if (t.getCell(i, 0).getText().contains("账号/卡号")) {
                bcm.setAccountNo(t.getCell(i, 1).getText());
                bcm.setAccountName(t.getCell(i, 3).getText());
            } else if (t.getCell(i, 0).getText().contains("查询起日")) {
                bcm.setQueryStartingDate(t.getCell(i, 1).getText());
                bcm.setQueryEndingDate(t.getCell(i, 3).getText());
            } else if (t.getCell(i, 0).getText().contains("打印时间")) {
                bcm.setPrintingTime(t.getCell(i, 1).getText());
                bcm.setSearchTeller(t.getCell(i, 3).getText());
            } else if (t.getCell(i, 0).getText().contains("证件种类")) {
                bcm.setIdType(t.getCell(i, 1).getText());
                bcm.setIdNo(t.getCell(i, 3).getText());
            } else if (t.getCell(i, 0).getText().contains("币种")) {
                bcm.setCurrency(t.getCell(i, 1).getText());
            }
        }
    }

    private List<BCMTran2> parseBCMTrans(String filePath) {
        List<BCMTran2> bcmTrans = new ArrayList<>();

        String transText = getPdfTextByStripper2(filePath);
        if (Strings.isNullOrEmpty(transText)) {
            return bcmTrans;
        }

        List<List<String>> tranFieldsList = parseTransTextToTranFieldsList(transText);
        for (int i = 0; i < tranFieldsList.size(); i++) {
            List<String> strings = tranFieldsList.get(i);
            String[] contents = strings.get(0).split(" ");

            if (!Pattern.matches("\\d{4}-\\d{2}-\\d{2}", contents[0])) {
                continue;
            }

            // 交易地点会有换行的场景，如果是换行，就是前面一行加上后面一行
            if (contents.length == 6) {
                BCMTran2 bcmTran2 = new BCMTran2();
                bcmTran2.setTransDate(contents[0]);

                String tradingPlace = "";
                if (i - 1 >0) {
                    List<String> frontStrings = tranFieldsList.get(i - 1);
                    String[] frontContents = frontStrings.get(0).split(" ");
                    if (!Pattern.matches("\\d{4}-\\d{2}-\\d{2}", frontContents[0])) {
                        tradingPlace += frontContents[0];
                    }
                }

                if (i + 1 < tranFieldsList.size()) {
                    List<String> nextStrings = tranFieldsList.get(i + 1);
                    String[] nextContents = nextStrings.get(0).split(" ");
                    if (!Pattern.matches("\\d{4}-\\d{2}-\\d{2}", nextContents[0])) {
                        tradingPlace += nextContents[0];
                    }
                }
                bcmTran2.setTradingPlace(tradingPlace);

                bcmTran2.setTransType(contents[1]);
                bcmTran2.setDcFlg(contents[2] + contents[3]);
                bcmTran2.setTransAmt(contents[4]);
                bcmTran2.setBalance(contents[5]);
                bcmTrans.add(bcmTran2);
            }
            if (contents.length == 7) {
                BCMTran2 bcmTran2 = new BCMTran2();
                bcmTran2.setTransDate(contents[0]);
                bcmTran2.setTradingPlace(contents[1]);
                bcmTran2.setTransType(contents[2]);
                bcmTran2.setDcFlg(contents[3] + contents[4]);
                bcmTran2.setTransAmt(contents[5]);
                bcmTran2.setBalance(contents[6]);
                bcmTrans.add(bcmTran2);
            }

        }

        return bcmTrans;
    }

    public static void main(String[] args) {
        BCMPdfParser2 bcmPdfParser = new BCMPdfParser2();
//        BCM2 bcm = bcmPdfParser.parseBCMPdf("D:\\data\\files\\BCM\\1120000420221103000554671918.pdf");
//        BCM2 bcm = bcmPdfParser.parseBCMPdf("D:\\data\\files\\BCM\\1120000420221108000559909839.pdf");
//        BCM2 bcm = bcmPdfParser.parseBCMPdf("D:\\data\\files\\BCM\\zd4g3dtt1570585160611713024_141560fa46fb3003497554676c975fc1_beehive-bcm_jyls-0.pdf");
        BCM2 bcm = bcmPdfParser.parseBCMPdf("D:\\data\\file\\交通银行\\20240326000002230577.pdf");

        String json = JsonUtils.convertObjectToJson(bcm);
        System.out.println(json);
    }

}
